package com.kongshidian.ui.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.annotation.view.ViewInject;

import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.adapter.MainProductRecommendAdapter;
import com.kongshidian.bean.BrandRecommend;
import com.kongshidian.bean.MainTopAdvertisement;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.bean.ProductCategory.AppLayout;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.BrandListActivity;
import com.kongshidian.ui.MainActivity;
import com.kongshidian.ui.ProductDetailActivity;
import com.kongshidian.ui.SearchListActivity;
import com.kongshidian.ui.SearchListActivity.SearchListAdapter;
import com.kongshidian.ui.view.AbsScrollGridView;
import com.kongshidian.ui.view.CountdownClock;
import com.kongshidian.ui.view.MyPagerGalleryView;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy;
import com.kongshidian.ui.view.ScrollViewRefreshProxy;
import com.kongshidian.ui.view.CountdownClock.ClockListener;
import com.kongshidian.ui.view.MyPagerGalleryView.MyOnItemClickListener;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.kongshidian.ui.view.ScrollViewRefreshProxy.OnRefreshActionListener;
import com.kongshidian.util.NetworkUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;



/***
 * 顶级空时店
 * @author ghg
 *
 */
@SuppressLint("HandlerLeak")
public class Copy_3_of_TopKSDFragment extends BaseFragment implements OnLoadDataActionListener{
	
	/** 顶部branner 滚动广告 */
	LinearLayout mMainPageLin; //滚动garllery
	MyPagerGalleryView mMainPageGalleryView; //滚动garllery
	LinearLayout mMainPageGalleryLin; //底部圆点容器

	private MainTopAdvertisement mTopAdvertisement;
	private List<MainTopAdvertisement.AdServing> mAdServings;

	//单品推荐
	private List<Product> mRecommend;
	private MainProductRecommendAdapter mProductRecommendAdapter;
	private static final String TAG = "TopKSDFragment"; 

	private int nowPage = 1;
	
  RelativeLayout mEmptyRelat;
	PullToRefreshGridView mRefreshGridView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	
	private Handler mHandler = new MyHandler(this);
	
	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState) { 
		return inflater.inflate(R.layout.fragement_topksd, container, false);  
	}  
	
	
	
	/**
	 * 创建以后做的事情
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
		
		/** 顶部branner 滚动广告 ,商家信息*/
		mMainPageLin	 = (LinearLayout) getView().findViewById(R.id.main_branner_lin);
		mMainPageGalleryView = 		(MyPagerGalleryView) getView().findViewById(R.id.main_branner_grally);
		mMainPageGalleryLin =		(LinearLayout) getView().findViewById(R.id.main_branner_butttom_lin);
		 
			
			
			//单品推荐视图
			mRefreshGridView= 	(PullToRefreshGridView)findViewById(R.id.main_product_recommend_grid_fresh);
			//空的时候显示
			mEmptyRelat = (RelativeLayout)findViewById(	R.id.search_grid_empty_brand_recommend );
			mRefreshGridView.setEmptyView(mEmptyRelat);
			mRefreshGridView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
			mRefreshGridView.getRefreshableView().setNumColumns(GridView.AUTO_FIT); // 2
			
			
			
			
			
			
			//将猜你喜欢改成下拉形式 ------------------------------------
			mProductRecommendAdapter = new MainProductRecommendAdapter(getActivity(), R.layout.item_main_product_recommend);
			mRefreshGridView.setAdapter(mProductRecommendAdapter);
			
			

			mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshGridView, Mode.BOTH,0,0);
			mLoadMoreProxy.setOnLoadDataActionListener(this);
			mRefreshGridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> paramAdapterView,
						View view, int position, long id) {
					Intent intent = new Intent(getActivity(),ProductDetailActivity.class);
					intent.putExtra("productID", mProductRecommendAdapter.getData().get(position).getId()+"");
					startActivity(intent);
				}

			});

			mLoadMoreProxy.refreshing();
	}

	

	
	

	
	
	
	
	
	/** 首页单品推荐  */
	private void getRecommendAsync(final int pageNumber) {
		new Thread(){
			public void run() {
				try {
					PageEntity<Product> entry = WebClient.getInstance(getActivity()).getRecommend(pageNumber);
					mRecommend = entry.getContent();
					
					mTopAdvertisement = WebClient.getInstance(getActivity()).adVertisement();
					mAdServings = mTopAdvertisement.getActiveServings();

					mHandler.sendEmptyMessage(0);
				} catch (WebException e) {
					App.showLog("Get Recommand fail=="+e.toString());
				}catch (Exception e) {
					App.showLog("Get Recommand fail=="+e.toString());
					App.showShortToast("未知错误");					
				}
			};
		}.start();


	}
	
	//Load Data Async End.................................................
		
		
		
		/**
		 * Handle下载
		 * @author ghg
		 *
		 */
		private  class MyHandler extends Handler{


			private final WeakReference<Fragment> mActivity; // activity弱引用

			public MyHandler(Copy_3_of_TopKSDFragment topKSDFragment) {  
				mActivity = new WeakReference<Fragment>(topKSDFragment);  
			}  

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				if( mActivity.get() != null ){ //activity若已销毁。不做任何处理
					switch (msg.what) {
					case 0:
						//获取广告
						initBranner();
						//单品推荐
						mProductRecommendAdapter.update(mRecommend);
						break;

					default:
						break;
					}
				}
			}
			
		
		}
		
		/** 初始化顶部branner滚动视图 */
		private void initBranner() {
			//判空。。
			if(mAdServings == null || mAdServings.size() == 0 ){
				mMainPageLin.setVisibility(View.GONE);
				return;
			}

			String[] urlImageList  = new String[mAdServings.size()];
			for (int i = 0; i < mAdServings.size(); i++) {
				urlImageList[i] = mAdServings.get(i).getAdMaterial().getPath();
			}	     

				mMainPageGalleryView.start(getActivity(), urlImageList, 3000,
				mMainPageGalleryLin, R.drawable.dot_focused, R.drawable.dot_normal);

				mMainPageGalleryView.setMyOnItemClickListener(new MyOnItemClickListener() {
				public void onItemClick(int curIndex) {
					App.showLog("下标=="+curIndex);
				}
			});
			
		}
		

		
		

		
		
		
		
		
		
		
		
		
		


		
		
			@Override
			public void onStop() {
				// TODO Auto-generated method stub
				mMainPageGalleryView.stopTimer();
				super.onStop();
			}
			
			@Override
			public void onDestroy() {
				super.onDestroy();
				mHandler.removeCallbacksAndMessages(null);
			}


			@Override
			public void onRefresh(int page) {
				if(page == 0){
						page = 1;
				}
				getRecommendAsync(page);  
				mRefreshGridView.onRefreshComplete();
			}
			@Override
			public void onLoadMore(int page) {
				nowPage ++;
				getRecommendAsync(page);  
				mRefreshGridView.onRefreshComplete();
			}
		
}
